package com.eian.boot.mybatis.config;

import com.eian.boot.common.core.factory.YmlPropertySourceFactory;
import com.eian.boot.mybatis.core.listener.AbstractFieldInsertListener;
import com.eian.boot.mybatis.core.listener.AbstractFieldUpdateListener;
import com.eian.boot.mybatis.core.model.BaseEntity;
import com.eian.boot.mybatis.plugin.CustomMessageCollector;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.logicdelete.LogicDeleteProcessor;
import com.mybatisflex.core.logicdelete.impl.IntegerLogicDeleteProcessor;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * MybatisPlus配置类
 *
 * @author alex.meng
 */
@Slf4j
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource(value = "classpath:common-mybatis.yml", factory = YmlPropertySourceFactory.class)
public class MyBatisFlexConfig implements MyBatisFlexCustomizer {
    @Value("${mybatis-flex.db-type}")
    private DbType dbType;
    @Resource
    private AbstractFieldInsertListener abstractFieldInsertListener;
    @Resource
    private AbstractFieldUpdateListener abstractFieldUpdateListener;

    public MyBatisFlexConfig() {
        //开启审计功能
        CustomMessageCollector collector = new CustomMessageCollector();
        AuditManager.setMessageCollector(collector);
        AuditManager.setAuditEnable(true);
    }

    /**
     * 逻辑删除处理器
     */
    @Bean
    public LogicDeleteProcessor logicDeleteProcessor() {
        return new IntegerLogicDeleteProcessor();
    }

    @Override
    public void customize(FlexGlobalConfig globalConfig) {
        // 数据库类型
        if (dbType == null) {
            dbType = DbType.POSTGRE_SQL;
        }
        globalConfig.setDbType(dbType);
        // 添加字段填充
        globalConfig.registerInsertListener(abstractFieldInsertListener, BaseEntity.class);
        globalConfig.registerUpdateListener(abstractFieldUpdateListener, BaseEntity.class);
    }
}
